package com.lzq.course.server.service;

import com.alibaba.fastjson.JSON;
import com.lzq.course.server.domain.Resource;
import com.lzq.course.server.dto.ResourceDto;
import com.lzq.course.server.mapper.ResourceMapper;
import com.lzq.course.server.util.CopyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class ResourceService {

    private final static Logger LOG = LoggerFactory.getLogger(ResourceService.class);

    @javax.annotation.Resource
    private ResourceMapper resourceMapper;

    /**
     * 查询
     * @return
     */
    public List<Resource> list() {
        List<Resource> resourceList = resourceMapper.selectByExample(null);
        return resourceList;
    }

    /**
     * 保存
     *
     * 解析成单个配置list 树形结构-> list
     * [{"id": "01", "name": "系统管理",
     *     "children": [{
     *             "id": "0101", "name": "用户管理", "page": "system/user",
     *             "children": [
     *                 {"id": "010101", "name": "保存", "request": ["/system/admin/user/list", "/system/admin/user/save"]},
     *                 ...
     * @param jsonStr 资源配置字符串
     */
    public void saveJson(String jsonStr) {
        List<ResourceDto> jsonList = JSON.parseArray(jsonStr, ResourceDto.class); // 嵌套关系
        List<ResourceDto> list = new ArrayList<>(); // 扁平化 用于存放平级

        // 判空
        if (!CollectionUtils.isEmpty(jsonList)) {
            for (int i = 0; i < jsonList.size(); i++) {
                ResourceDto resourceDto = jsonList.get(i); // 第一次为根
                resourceDto.setParent(""); // 父节点的父亲为空
                add(resourceDto, list);
            }
        }

        LOG.info("资源配置共{}条", list.size());

        // 遍历插入数据库 首先清空数据库表
        resourceMapper.deleteByExample(null);
        for (ResourceDto resourceDto : list) {
            Resource resource = CopyUtil.copy(resourceDto, Resource.class);
            insert(resource);
        }
    }

    /**
     * 插入 id是自定义好的 不是生成的
     */
    public void insert(Resource resource) {
        resourceMapper.insert(resource);
    }

    /**
     * 删除
     * @param id
     */
    public void delete(String id) {
        resourceMapper.deleteByPrimaryKey(id);
    }

    /**
     * 插入资源
     * 【递归函数】
     * @param resourceDto 资源
     * @param list 放入集合
     */
    public void add(ResourceDto resourceDto, List<ResourceDto> list) {
        list.add(resourceDto); // 先把父节点放入
        List<ResourceDto> children = resourceDto.getChildren();
        if (!CollectionUtils.isEmpty(children)) { // 该节点还有子节点
            for (ResourceDto child : children) {
                child.setParent(resourceDto.getId());
                add(child, list); // 添加子节点到集合
            }
        }
    }
}
